package cn.iocoder.yudao.module.scrm.controller.admin.marketing;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
import cn.iocoder.yudao.framework.common.util.number.NumberUtils;
import cn.iocoder.yudao.module.scrm.controller.admin.customer.vo.CustomerRespVO;
import cn.iocoder.yudao.module.scrm.controller.admin.marketing.vo.transmit.MarketingTransmitPageReqVO;
import cn.iocoder.yudao.module.scrm.controller.admin.marketing.vo.transmit.MarketingTransmitRespVO;
import cn.iocoder.yudao.module.scrm.controller.admin.marketing.vo.transmit.MarketingTransmitSaveReqVO;
import cn.iocoder.yudao.module.scrm.dal.dataobject.customer.CustomerDO;
import cn.iocoder.yudao.module.scrm.dal.dataobject.marketing.MarketingTransmitDO;
import cn.iocoder.yudao.module.scrm.service.marketing.transmit.MarketingTransmitService;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;
import java.util.stream.Stream;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;

import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertListByFlatMap;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.*;


@Tag(name = "管理后台 - 营销转发")
@RestController
@RequestMapping("/scrm/marketing-transmit")
@Validated
public class MarketingTransmitController {

    @Resource
    private MarketingTransmitService marketingTransmitService;

    @Resource
    private DeptApi deptApi;
    @Resource
    private AdminUserApi adminUserApi;

    @PostMapping("/create")
    @Operation(summary = "创建营销转发")
    @PreAuthorize("@ss.hasPermission('scrm:marketing-transmit:create')")
    public CommonResult<Integer> createMarketingTransmit(@Valid @RequestBody MarketingTransmitSaveReqVO createReqVO) {
        return success(marketingTransmitService.createMarketingTransmit(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新营销转发")
    @PreAuthorize("@ss.hasPermission('scrm:marketing-transmit:update')")
    public CommonResult<Boolean> updateMarketingTransmit(@Valid @RequestBody MarketingTransmitSaveReqVO updateReqVO) {
        marketingTransmitService.updateMarketingTransmit(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除营销转发")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('scrm:marketing-transmit:delete')")
    public CommonResult<Boolean> deleteMarketingTransmit(@RequestParam("id") Integer id) {
        marketingTransmitService.deleteMarketingTransmit(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得营销转发")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('scrm:marketing-transmit:query')")
    public CommonResult<MarketingTransmitRespVO> getMarketingTransmit(@RequestParam("id") Integer id) {
        MarketingTransmitDO marketingTransmit = marketingTransmitService.getMarketingTransmit(id);
        return CommonResult.success(buildTransmitDetail(marketingTransmit));
    }

    @GetMapping("/page")
    @Operation(summary = "获得营销转发分页")
    @PreAuthorize("@ss.hasPermission('scrm:marketing-transmit:query')")
    public CommonResult<PageResult<MarketingTransmitRespVO>> getMarketingTransmitPage(@Valid MarketingTransmitPageReqVO pageReqVO) {
        PageResult<MarketingTransmitDO> pageResult = marketingTransmitService.getMarketingTransmitPage(pageReqVO);
        // 拼接数据
        return success(new PageResult<>(buildTransmitDetailList(pageResult.getList()), pageResult.getTotal()));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出营销转发 Excel")
    @PreAuthorize("@ss.hasPermission('scrm:marketing-transmit:export')")
    @OperateLog(type = EXPORT)
    public void exportMarketingTransmitExcel(@Valid MarketingTransmitPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<MarketingTransmitDO> list = marketingTransmitService.getMarketingTransmitPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "营销转发.xls", "数据", MarketingTransmitRespVO.class, buildTransmitDetailList(list));
    }

    private MarketingTransmitRespVO buildTransmitDetail(MarketingTransmitDO transmitDO) {
        if (transmitDO == null) {
            return null;
        }
        return buildTransmitDetailList(Collections.singletonList(transmitDO)).get(0);
    }

    public List<MarketingTransmitRespVO> buildTransmitDetailList(List<MarketingTransmitDO> list) {
        if (CollUtil.isEmpty(list)) {
            return java.util.Collections.emptyList();
        }
        // 1.1 获取创建人、负责人列表
        Map<Long, AdminUserRespDTO> userMap = adminUserApi
                .getUserMapNotCheckDataPermission(convertListByFlatMap(list, transmitDO -> Stream.of(NumberUtils.parseLong(transmitDO.getCreator()), transmitDO.getUserId())));
        Map<Long, DeptRespDTO> deptMap = deptApi.getDeptMapNotCheckDataPermission(convertSet(userMap.values(), AdminUserRespDTO::getDeptId));
        // 2. 转换成 VO
        return BeanUtils.toBean(list, MarketingTransmitRespVO.class, transmitRespVO -> {
            // 2.1 设置创建人、负责人名称
            MapUtils.findAndThen(userMap, NumberUtils.parseLong(String.valueOf(transmitRespVO.getUserId())), user -> transmitRespVO.setName(user.getNickname()));
            MapUtils.findAndThen(userMap, transmitRespVO.getUserId(), user -> {
                MapUtils.findAndThen(deptMap, user.getDeptId(), dept -> transmitRespVO.setDept(dept.getName()));
            });
        });
    }

}